<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\CommonController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUserGift;
use App\Models\UserDrawAddress;
use App\Models\UserInfo;
use App\Models\UserWechatInfo;
use App\Validate\AnswerActivityUserGiftValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\SmallPay;
use App\Http\Controllers\SmallPayV3;
use App\Models\AnswerActivityPacketTransfer;
use App\Models\AnswerActivityUserUnit;

/**
 * 用户活动获取礼物
 */
class AnswerActivityUserGiftController extends CommonController
{

    public $model = null;
    public $activityModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityUserGift();
        $this->activityModel = new AnswerActivity();
        $this->validate = new AnswerActivityUserGiftValidate();
    }

    /**
     * 获取有礼物的单位列表（用于筛选）
     * @param act_id int 活动id
     */
    public function getUnitList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('unit_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $act_info = $this->activityModel->detail($this->request->act_id, null, null);

        if (empty($act_info)) {
            return $this->returnApi(201, '参数错误');
        }
        if ($act_info['prize_form'] == 1) {
            return $this->returnApi(201, '此活动为排名类活动');
        }
        $answerActivityGiftModel = new AnswerActivityGift();
        $res = $answerActivityGiftModel->getUnitList($this->request->act_id);

        if (empty($res)) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '获取成功', true, $res);
    }


    /**
     * 获取用户礼物列表
     * @param act_id int 活动id
     * @param page int 页码
     * @param limit int 分页大小
     * @param state string 礼物状态 1未发放 2已发放 3未发货 4邮递中 5已到货  6 未领取  7 已领取  8 红包发放中
     * @param type int 1文化红包 2精美礼品
     * @param unit_id string 单位id  空或null 代表  全部  0代表系统
     * @param keywords string 搜索关键词
     * @param start_time datetime 开始时间    数据格式  年月日
     * @param end_time datetime 结束时间
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $act_info = $this->activityModel->detail($this->request->act_id, null, null);

        if (empty($act_info)) {
            return $this->returnApi(201, '参数错误');
        }
        if ($act_info['prize_form'] == 1) {
            return $this->returnApi(201, '此活动为排名类活动');
        }
        $res = $this->model->lists($this->request->act_id, null, $this->request->keywords, $this->request->type, $this->request->state, $this->request->unit_id, $this->request->start_time, $this->request->end_time, $page, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        $userDrawAddressModel = new UserDrawAddress();
        $activityUserUnitModel = new AnswerActivityUserUnit();
        $userInfoModel = new UserInfo();
        foreach ($res['data'] as $key => $val) {
            if ($act_info['node'] != 1) {
                if ($val['unit_id']) {
                    $res['data'][$key]['unit_name'] = AnswerActivityUnit::where('act_id', $this->request->act_id)->where('id', $val['unit_id'])->value('name');
                }
            } else {
                $res['data'][$key]['unit_name'] = null;
            }
            $res['data'][$key]['user_wechat_info'] = $userInfoModel->getWechatInfo($val['user_guid']);
            $res['data'][$key]['user_draw_address_info'] = $userDrawAddressModel->detail($val['user_guid'], 1, $this->request->act_id);
            $res['data'][$key]['user_unit_info'] =  $activityUserUnitModel->getUserUnitInfo($val['user_guid'], $this->request->act_id);
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            if ($val['state'] == 1) {
                //获取转账失败原因
                $res['data'][$key]['fail_reason'] = AnswerActivityPacketTransfer::where('out_detail_no', $val['order_id'])->value('fail_reason');
            }
        }

        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 奖品领取或发奖
     * @param ids 奖品id 多个逗号拼接
     * @param state 奖品id 4 已发货  7 已领取
     */
    public function userGiftGrant()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('user_gift_grant')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        DB::beginTransaction();
        try {
            $this->model->giftGrant($this->request->ids, $this->request->state);
            DB::commit();
            return $this->returnApi(200, '操作成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 红包转账失败，进行重新转账
     * @param id 奖品id 
     */
    public function userPacketTransfer()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('user_packet_transfer')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $answerActivityUserGiftModel = new AnswerActivityUserGift();
        $answerActivityUserGiftInfo = $answerActivityUserGiftModel->where('id', $this->request->id)->first();
        if (empty($answerActivityUserGiftInfo) || $answerActivityUserGiftInfo->type != 1 || $answerActivityUserGiftInfo->state != 1 || empty($answerActivityUserGiftInfo->price)) {
            return $this->returnApi(201, '参数错误');
        }

        $act_info = AnswerActivity::where('id', $answerActivityUserGiftInfo->act_id)->where('is_del', 1)->first();
        if (
            $act_info['start_time'] > date('Y-m-d H:i:s') &&
            !in_array(
                $answerActivityUserGiftInfo->user_guid,
                [
                    //  'e01452dc7ad3300aa43e1e88fbd91c5f', //15102892664
                    //  '559bf2d43bb0394ede9f16302ac9158b', //18081838416
                ]
            )
        ) {
            return $this->returnApi(201, '活动未开始,不能发送红包');
        }
        $act_name = $act_info['title'];

        //正常转账流程
        $user_guid = $answerActivityUserGiftInfo->user_guid;
        $order_id = $answerActivityUserGiftInfo->order_id;
        $packet_msg = $act_name;
        $price = $answerActivityUserGiftInfo->price * 100;

        if ($price > 30000) {
            return $this->returnApi(201, '红包金额不能超过300元'); //初步限制下，不能超过300元
        }

        //  $price = 0.3 * 100; //TODO测试使用

        $userWechatModel = new UserWechatInfo();
        $wechat_user_info = $userWechatModel->where('user_guid', $user_guid)->where('node', 'YXYZ')->first();

        if (empty($wechat_user_info)) {
            return $this->returnApi(201, '用户获取失败,不能转账');
        }
        //进行转账操作，写入正在转账中
        $answerActivityUserGiftModel->where('order_id', $order_id)->update(['pay_time' => date('Y-m-d H:i:s'), 'state' => 8]); //这里 8 是发放红包中
        $smallPayModel = new SmallPayV3();
        $res = $smallPayModel->wechatTransfer($order_id, $price, $wechat_user_info['open_id'], '竞答活动红包', $packet_msg);
        if ($res !== true) {
            Log::error("转账失败,理由为" . $res . ",竞答活动用户获奖数据id：" . $this->request->id . ';订单号为：' . $order_id);
            $answerActivityUserGiftModel->where('order_id', $order_id)->update(['pay_time' => date('Y-m-d H:i:s'), 'state' => 1, 'fail_reason' => $res]); // 改为 1 ，未发放，不影响之前逻辑

            return $this->returnApi(202, $res);
        }
        return $this->returnApi(200, '转账中，转账结果正在查询中');
    }


    /**
     * 红包转账失败，进行重新转账
     * @param id 奖品id 
     */
    public function _userPacketTransfer()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('user_packet_transfer')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $answerActivityUserGiftModel = new AnswerActivityUserGift();
        $answerActivityUserGiftInfo = $answerActivityUserGiftModel->where('id', $this->request->id)->first();
        if (empty($answerActivityUserGiftInfo) || $answerActivityUserGiftInfo->type != 1 || $answerActivityUserGiftInfo->state != 1 || empty($answerActivityUserGiftInfo->price)) {
            return $this->returnApi(201, '参数错误');
        }

        $act_name = AnswerActivity::where('id', $answerActivityUserGiftInfo->act_id)->value('title');
        //正常转账流程
        $user_guid = $answerActivityUserGiftInfo->user_guid;
        $order_id = $answerActivityUserGiftInfo->order_id;
        $packet_msg = $act_name;
        $price = $answerActivityUserGiftInfo->price * 100;

        //  $price = 0.3 * 100; //TODO测试使用

        $userWechatModel = new UserWechatInfo();
        $wechat_user_info = $userWechatModel->where('user_guid', $user_guid)->where('node', 'YXYZ')->first();

        if (empty($wechat_user_info)) {
            return $this->returnApi(201, '用户获取失败,不能转账');
        }

        $smallPayModel = new SmallPay();
        $res = $smallPayModel->transfer($order_id, $price, $wechat_user_info['open_id'], $packet_msg);

        //写入转账日志
        if (!empty($res['data'])) {
            $packet_transfer_model = new AnswerActivityPacketTransfer();
            $packet_transfer_model->insert($res['data']);
        }

        if ($res['code'] == 200) {
            $answerActivityUserGiftModel->where('order_id', $order_id)->update(['pay_time' => $res['pay_time'], 'state' => 2]);
            return $this->returnApi(200, '转账成功', true);
        }
        return $this->returnApi(202, $res['msg'] ?? '转账失败');
    }
}
